<template>
  <div class="create-video">
    <div class="header">
      <div class="header-content">
        <h1 class="page-title">🎬 PPT视频生成</h1>
        <p class="page-subtitle">将您的PPT演示文稿转换为高质量视频</p>
      </div>
      <el-button class="back-btn" @click="$router.push('/')">
        <el-icon><arrow-left /></el-icon>
        返回首页
      </el-button>
    </div>
    
    <div class="content">
      <!-- 上传区域 -->
      <div v-if="videoStatus === 'idle'" class="upload-section">
        <div class="upload-card">
          <div class="card-header">
            <div class="header-icon">📤</div>
            <div class="header-text">
              <h3>上传PPT文件</h3>
              <p>开始您的视频创作之旅</p>
            </div>
          </div>
          
          <el-upload
            class="upload-area"
            drag
            action="http://localhost:3002/api/upload-and-generate"
            :headers="{
              'Accept': 'application/json'
            }"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept=".ppt,.pptx"
            name="file"
          >
            <div class="upload-content">
              <div class="upload-icon">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              </div>
              <div class="upload-text">
                <p class="primary-text">将PPT文件拖到此处</p>
                <p class="secondary-text">或 <em class="click-text">点击上传</em></p>
              </div>
              <div class="upload-tips">
                <span class="tip-badge">💡 支持格式</span>
                <span class="tip-text">PPT、PPTX 文件</span>
              </div>
            </div>
          </el-upload>
        </div>
      </div>

      <!-- 视频生成进度 -->
      <div v-if="videoStatus !== 'idle'" class="progress-section">
        <div class="progress-card">
          <div class="card-header">
            <div class="header-icon animate-pulse">⚡</div>
            <div class="header-text">
              <h3>视频生成中</h3>
              <p>AI正在处理您的PPT文件</p>
            </div>
          </div>
          
          <div class="progress-content">
            <div class="file-info" v-if="fileName">
              <div class="file-icon">📄</div>
              <div class="file-details">
                <h4>{{ fileName }}</h4>
                <p>正在转换为精美视频...</p>
              </div>
            </div>
            
            <div class="progress-wrapper">
              <el-progress 
                :percentage="videoProgress" 
                :status="videoStatus === 'failed' ? 'exception' : videoStatus === 'completed' ? 'success' : ''"
                :stroke-width="12"
                :text-inside="false"
                class="progress-bar"
              />
              <div class="progress-text">{{ videoProgress.toFixed(1) }}%</div>
            </div>
            
            <div class="status-message">
              <div v-if="videoStatus === 'processing'" class="status-processing">
                <div class="loading-dots">
                  <span></span><span></span><span></span>
                </div>
                <span>正在生成视频，请稍候...</span>
              </div>
              <div v-else-if="videoStatus === 'completed'" class="status-success">
                <el-icon class="success-icon"><check /></el-icon>
                <span>视频生成完成！即将跳转到视频列表...</span>
              </div>
              <div v-else-if="videoStatus === 'failed'" class="status-error">
                <el-icon class="error-icon"><close /></el-icon>
                <span>{{ videoError }}</span>
              </div>
            </div>
            
            <div v-if="videoStatus === 'failed'" class="retry-section">
              <el-button class="retry-btn" type="primary" @click="resetUpload">
                <el-icon><refresh /></el-icon>
                重新上传
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, ArrowLeft, Check, Close, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import api from '@/api'
import request, { ApiError } from '@/utils/request'

const router = useRouter()

interface FileInfo {
  name: string
  size: number
  type: string
  path: string
  url: string
}

const fileInfo = ref<FileInfo | null>(null)
const fileName = ref<string>('')
const videoStatus = ref<'idle' | 'processing' | 'completed' | 'failed'>('idle')
const videoProgress = ref(0)
const videoError = ref<string>('')
const fileUrl = ref('')
const videoUrl = ref('')

// 上传前检查
const beforeUpload = (file: File) => {
  const isPPT = file.type === 'application/vnd.ms-powerpoint' || 
                file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  
  if (!isPPT) {
    ElMessage.error('只能上传 PPT 或 PPTX 文件！')
    return false
  }
  
  // 设置文件名
  fileName.value = file.name.replace(/\.(ppt|pptx)$/i, '')
  
  return true
}

// 上传成功处理 - 自动开始生成视频
const handleUploadSuccess = async (response: any, file: any) => {
  console.log('上传响应:', response)
  
  try {
    // 设置文件信息
    fileInfo.value = {
      name: file.name,
      size: file.size,
      type: file.type,
      path: response.filePath || '',
      url: response.fileUrl || ''
    }
    
    fileName.value = file.name.replace(/\.(ppt|pptx)$/i, '')
    
    ElMessage.success('文件上传成功，开始生成视频...')
    
    // 立即开始生成视频
    await startVideoGeneration(response, file)
    
  } catch (error) {
    console.error('处理上传响应失败:', error)
    ElMessage.error('文件上传失败')
    videoStatus.value = 'failed'
    videoError.value = '处理上传文件时出错'
  }
}

// 开始视频生成
const startVideoGeneration = async (uploadResponse: any, file: any) => {
  videoStatus.value = 'processing'
  videoProgress.value = 0
  
  // 模拟进度更新，保留两位小数
  const progressInterval = setInterval(() => {
    if (videoProgress.value < 85) {
      const increment = Math.random() * 8
      videoProgress.value = Math.min(85, parseFloat((videoProgress.value + increment).toFixed(2)))
    }
  }, 1000)

  try {
    // 调用视频生成API
    const response = await request.post('/api/video/generate', {
      fileName: fileName.value,
      filePath: uploadResponse.filePath || uploadResponse.path,
      fileUrl: uploadResponse.fileUrl || uploadResponse.url,
      originalName: file.name
    }).catch((err: ApiError) => {
      console.error('生成视频请求失败:', err.response?.data || err.message)
      return null
    })

    if (!response?.data) {
      clearInterval(progressInterval)
      videoStatus.value = 'failed'
      videoError.value = '视频生成失败'
      ElMessage.error('视频生成失败')
      return
    }

    if (response.data.success || response.data.code === 0) {
      const videoId = response.data.videoId
      console.log('视频生成任务已开始，videoId:', videoId)
      
      // 开始轮询检查视频生成状态
      let checkCount = 0
      const maxChecks = 120 // 最多检查120次（约10分钟，因为PPT转视频可能需要较长时间）
      
      const checkVideoStatus = async () => {
        try {
          checkCount++
          const statusResponse = await api.get(`/api/video/status/${videoId}`)
          console.log(`第${checkCount}次检查视频状态:`, statusResponse.data)
          
          if (statusResponse.data.code === 0) {
            const { status, videoPath, fileSize } = statusResponse.data.data
            
            if (status === 'completed') {
              // 视频生成完成
              clearInterval(progressInterval)
              videoProgress.value = 100.00
              videoStatus.value = 'completed'
              ElMessage.success('视频生成完成！')
              
              console.log(`视频生成成功: ${videoPath}, 文件大小: ${fileSize}KB`)
              
              // 保存视频元数据（包含原始PPT文件名）
              try {
                await api.post('/api/videos/metadata', {
                  videoId: videoId,
                  originalName: fileName.value,
                  fileName: fileName.value,
                  filePath: uploadResponse.filePath || uploadResponse.path
                })
                console.log('视频元数据保存成功')
              } catch (error) {
                console.warn('保存视频元数据失败:', error)
              }
              
              // 3秒后自动跳转到视频列表
              setTimeout(() => {
                router.push('/videos')
              }, 3000)
              
              return // 停止轮询
            } else if (status === 'processing') {
              // 仍在处理中，更新进度
              videoProgress.value = Math.min(95, parseFloat((85 + (checkCount / maxChecks) * 10).toFixed(2)))
              
              if (checkCount >= maxChecks) {
                // 超时
                clearInterval(progressInterval)
                videoStatus.value = 'failed'
                videoError.value = '视频生成超时，请重试'
                ElMessage.error('视频生成超时')
                return
              }
              
              // 继续检查（PPT转视频耗时较长，每2秒检查一次）
              setTimeout(checkVideoStatus, 2000)
            } else {
              // 未知状态
              console.warn('未知的视频状态:', status)
              if (checkCount >= maxChecks) {
                clearInterval(progressInterval)
                videoStatus.value = 'failed'
                videoError.value = '视频生成状态异常'
                ElMessage.error('视频生成失败')
                return
              }
              setTimeout(checkVideoStatus, 5000)
            }
          } else {
            console.error('检查视频状态失败:', statusResponse.data)
            if (checkCount >= maxChecks) {
              clearInterval(progressInterval)
              videoStatus.value = 'failed'
              videoError.value = '无法检查视频生成状态'
              ElMessage.error('视频生成失败')
              return
            }
            setTimeout(checkVideoStatus, 5000)
          }
        } catch (error) {
          console.error('检查视频状态时发生错误:', error)
          if (checkCount >= maxChecks) {
            clearInterval(progressInterval)
            videoStatus.value = 'failed'
            videoError.value = '检查视频状态失败'
            ElMessage.error('视频生成失败')
            return
          }
          setTimeout(checkVideoStatus, 5000)
        }
      }
      
      // 延迟3秒后开始第一次检查（给后端时间启动Python脚本）
      setTimeout(checkVideoStatus, 3000)
      
    } else {
      clearInterval(progressInterval)
      videoStatus.value = 'failed'
      videoError.value = response.data.message || '视频生成失败'
      ElMessage.error(videoError.value)
    }
  } catch (error) {
    clearInterval(progressInterval)
    console.error('生成视频失败:', error)
    videoStatus.value = 'failed'
    videoError.value = '视频生成过程中发生错误'
    ElMessage.error('视频生成失败')
  }
}

// 上传失败处理
const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  ElMessage.error(error?.response?.data?.message || '文件上传失败，请重试')
  videoStatus.value = 'failed'
  videoError.value = '文件上传失败'
}

// 重置上传
const resetUpload = () => {
  fileInfo.value = null
  fileName.value = ''
  videoStatus.value = 'idle'
  videoProgress.value = 0
  videoError.value = ''
  fileUrl.value = ''
  videoUrl.value = ''
}
</script>

<style scoped>
.create-video {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 30px 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 30px;
  background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border: none;
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
  font-weight: 400;
}

.back-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  border: none;
  padding: 12px 24px;
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.back-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.content {
  max-width: 700px;
  margin: 0 auto;
}

.upload-section,
.progress-section {
  margin-bottom: 30px;
}

.upload-card,
.progress-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  border: none;
  padding: 30px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.upload-card::before,
.progress-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.05), transparent);
  transition: all 0.8s;
}

.upload-card:hover::before,
.progress-card:hover::before {
  left: 100%;
}

.upload-card:hover,
.progress-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.header-icon {
  font-size: 32px;
  margin-right: 15px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}

.header-icon.animate-pulse {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.header-text {
  flex: 1;
}

.header-text h3 {
  margin: 0 0 5px 0;
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-text p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.upload-area {
  width: 100%;
  position: relative;
  z-index: 1;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 250px;
  border: 3px dashed rgba(102, 126, 234, 0.3);
  border-radius: 16px;
  background: linear-gradient(145deg, #f8f9fc, #ffffff);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.el-upload-dragger:hover {
  border-color: rgba(102, 126, 234, 0.8);
  background: linear-gradient(145deg, #f0f4ff, #f8f9fc);
  transform: scale(1.02);
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.15);
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.upload-icon {
  font-size: 64px;
  margin-bottom: 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  filter: drop-shadow(0 4px 8px rgba(0,0,0,0.1));
}

.upload-text {
  text-align: center;
  margin-bottom: 20px;
}

.primary-text {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}

.secondary-text {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.click-text {
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 600;
  text-decoration: none;
}

.upload-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px 20px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 25px;
  backdrop-filter: blur(10px);
}

.tip-badge {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.tip-text {
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
}

.progress-content {
  text-align: center;
  padding: 20px 0;
  position: relative;
  z-index: 1;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40px;
  padding: 20px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 16px;
  backdrop-filter: blur(10px);
}

.file-icon {
  font-size: 48px;
  margin-right: 20px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}

.file-details {
  text-align: left;
}

.file-details h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.file-details p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.progress-wrapper {
  margin: 40px 0;
  position: relative;
}

.progress-bar {
  margin-bottom: 15px;
}

.progress-text {
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.status-message {
  margin: 40px 0;
  padding: 20px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
}

.status-processing {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.status-success {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.status-error {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
  animation: loading 1.4s infinite both;
}

.loading-dots span:nth-child(1) { animation-delay: 0s; }
.loading-dots span:nth-child(2) { animation-delay: 0.2s; }
.loading-dots span:nth-child(3) { animation-delay: 0.4s; }

@keyframes loading {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1.2); opacity: 1; }
}

.success-icon,
.error-icon {
  font-size: 20px;
}

.retry-section {
  margin-top: 40px;
}

.retry-btn {
  background: linear-gradient(135deg, #f56c6c, #ff8a80);
  color: #fff;
  border: none;
  padding: 12px 30px;
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 15px rgba(245, 108, 108, 0.3);
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(245, 108, 108, 0.4);
}

/* 页面进入动画 */
.upload-section,
.progress-section {
  animation: slideInUp 0.6s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-video {
    padding: 20px 15px;
  }
  
  .content {
    max-width: 100%;
  }
  
  .header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
    text-align: center;
    padding: 25px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .upload-card,
  .progress-card {
    padding: 25px 20px;
  }
  
  .el-upload-dragger {
    height: 200px;
  }
  
  .upload-icon {
    font-size: 48px;
  }
  
  .primary-text {
    font-size: 18px;
  }
  
  .file-info {
    flex-direction: column;
    text-align: center;
  }
  
  .file-icon {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .file-details {
    text-align: center;
  }
}

@media (max-width: 480px) {
  .upload-tips {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-icon {
    font-size: 28px;
  }
  
  .header-text h3 {
    font-size: 18px;
  }
}
</style>
